package com.zdy.boot.upload.core.scan;

import cn.hutool.core.lang.UUID;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.zdy.boot.upload.core.job.handler.AbstractJobHandler;
import com.zdy.boot.upload.domain.PicEntity;
import com.zdy.boot.upload.domain.PicRequest;
import com.zdy.boot.upload.utils.FileUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @author sdy
 * @description
 * @date 2025/2/9
 */
@Slf4j
@Component
public class ScanPicJob extends AbstractJobHandler {

    /**
     * 单次请求最多上传文件数量
     */
    @Value("${seal.pic.maxUpSize}")
    private int maxUploadSize;
    @Value("${seal.pic.url}")
    private String picUrl;
    @Value("${seal.pic.path}")
    private String picPath;
    @Value("${seal.pic.type}")
    private String fileType;

    @Override
    public void executeJob(String param) {
        try {
            handle();
        } catch (Exception ex) {
            log.error("上传图片异常", ex);
        }
    }

    private void handle() {
        log.info("开始处理图片");
        // 读取图片文件列表
        try(Stream<Path> pathStream = Files.walk(Paths.get(picPath))) {
            List<Path> batchList = new ArrayList<>();
            pathStream.filter(p -> FileUtils.filter(p, fileType)).forEach(p -> {
                // 加入批次
                batchList.add(p);
                // 分批处理防止内存泄漏
                if (batchList.size() == maxUploadSize) {
                    // 上传
                    upload(batchList);
                    // 清理列表
                    batchList.clear();
                }
            });
            // 最后一次上传，防止遗漏
            if (!CollectionUtils.isEmpty(batchList)) {
                upload(batchList);
            }
        } catch (IOException e) {
            log.error("读取本地文件异常：" + e.getMessage(), e);
            throw new RuntimeException(e.getMessage());
        }
        log.info("结束处理图片");
    }

    /**
     * 上传文件
     * @param paths 文件列表
     */
    private void upload(List<Path> paths) {
        try {
            if (!StringUtils.hasText(picUrl)) {
                log.error("请求地址未配置，停止上传");
                return;
            }
            log.info("图片上传地址：{}", picUrl);
            // 转换文件
            List<PicEntity> entities = paths.stream().map(PicEntity::new).collect(Collectors.toList());
            // 上传文件
            PicRequest request = new PicRequest();
            request.setBatchId(UUID.fastUUID().toString(true));
            request.setPicList(entities);
            log.info("图片上传参数：{}", request.getPicName());
            String resp = HttpUtil.post(picUrl, JSONUtil.toJsonStr(request));
            log.info("结束上传图片:{}", resp);
            // 删除文件
            FileUtils.delete(paths);
        } catch (Exception ex) {
            log.info("上传图片异常：{}", ex.getMessage(), ex);
        }
    }

}
